/**
 * Company : Thai Informatic System Co., Ltd.
 * Created By : Dr.Tree
 * Created On : Mar 20, 2012  10:47:04 AM 
 * e-Mail : chatree@tis.co.th
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : sap.business.fi.outbound
 * File Name : FiArinvoicereceOutbService.java
 * TODO
 */
package sap.business.fi.outbound;

import java.util.ArrayList;
import java.util.List;

import jpa.entitys.synchro.staging.FiApinvoicerentOutb;
import jpa.entitys.synchro.staging.FiArinvoicereceOutb;
import jpa.entitys.synchro.staging.FiVcGlpostingOutb;
import jpa.service.common.SessionEntityManager;
import jpa.service.synchro.staging.FiApinvoicerentOutbServices;
import jpa.service.synchro.staging.FiArinvoicereceOutbServices;

import org.apache.log4j.Logger;

import promis.utility.CommonService;

import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoTable;

import sap.business.commons.SynchroOutAbstract;
import sap.business.commons.services.CommonJCOReturn;
import sap.jco.client.Connection;

/**
 * @author chatree
 *
 */
public class FiArinvoicereceOutbService extends SynchroOutAbstract {
	
	private static final Logger log = Logger.getLogger(FiArinvoicereceOutbService.class);
	private FiArinvoicereceOutbServices fiArinvoicereceOutbServ;	

	/**
	 * 
	 */
	public FiArinvoicereceOutbService() {
		// TODO Auto-generated constructor stub
		try {
			super.emSynchro = new SessionEntityManager().CreatedEntityManager();
		} catch (Exception e) {
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}
	}
	
	@Override
	public void SynchroToSap(JCoFunction jcoFunction, JCoTable jcoTable, List<?> value_list) throws Exception {
		// TODO Auto-generated method stub
		if(!jcoTable.isEmpty())
		{
			log.info("Bapi = "+ sap_bapi +", table "+ sap_table +" is not Empty ");
			return;
		}	
		
		if(!CommonService.IsNull(value_list)){
			
			log.info("value_list.size : " + value_list.size());			
			log.info("table.getNumRows : " + jcoTable.getNumRows());
			
			for (Object obj : value_list) 
	        {
				FiArinvoicereceOutb model = (FiArinvoicereceOutb)obj;
				log.info("InstanceNo = " + model.getInstanceNo() + " -- PROMIS_TXN_ID = " +  model.getPromisStagingId());
				jcoTable.appendRow();
				jcoTable.setValue("PROMIS_TXN_ID", model.getPromisStagingId());
				jcoTable.setValue("INTERFACE_NO", "FI-T1-040");
				jcoTable.setValue("BUKRS", model.getSapCompanyCode());
				jcoTable.setValue("BLDAT", model.getVoucherDate());
				jcoTable.setValue("BUDAT", model.getVoucherDate());
				jcoTable.setValue("WAERS", model.getCurrency());
				jcoTable.setValue("KURSF", model.getExchangeRate());
				jcoTable.setValue("BKTXT", model.getDescription());
				jcoTable.setValue("CHARGE_CODE", model.getChargeCode());
				jcoTable.setValue("SERVICE_FLAG", model.getServiceVatFlag());
				jcoTable.setValue("HKONT", model.getCustomerCode());
				jcoTable.setValue("INCVAT", model.getAmountReceived());
				jcoTable.setValue("FWBAS", model.getVatReceived());
				jcoTable.setValue("MWSKZ", model.getVatCode());
				jcoTable.setValue("ZFBDT", model.getVoucherDate());
				jcoTable.setValue("ZLSCH", model.getReceivedType());
				jcoTable.setValue("ZUONR", model.getReceiptDocNo());
				jcoTable.setValue("SGTXT", model.getRemarks());
				jcoTable.setValue("QSSKZ", model.getTaxTypeCode());
				jcoTable.setValue("QSSHB", model.getWhtBaseAmount());
				jcoTable.setValue("QBSHB", model.getWhtAmount());
				jcoTable.setValue("XREF2", model.getRefDocument());
				jcoTable.setValue("EXCVAT", model.getVatBaseReceived());
				jcoTable.setValue("PLANT_CODE", model.getSapPlantCode());
				jcoTable.setValue("PROMIS_UNIT_CODE", model.getUnitNumber());
				jcoTable.setValue("SPESW", model.getBankCharge());
				jcoTable.setValue("DUEON", model.getChequeDueDate());
				jcoTable.setValue("WDATE", model.getVoucherDate());
				jcoTable.setValue("WNAME", model.getChequePayeeAc());
				jcoTable.setValue("WORT1", model.getCompanyAddress());
				jcoTable.setValue("WBZOG", model.getCustomerName());
				jcoTable.setValue("WORT2", model.getAddressCustomer());
				jcoTable.setValue("BOENO", model.getChequeNumber());
				jcoTable.setValue("BANK", model.getChequeIssuingBank());
				jcoTable.setValue("ACCOU", model.getChequePayerAcNo());
				jcoTable.setValue("INVOICE_NO", model.getInvoiceRefNo());
				jcoTable.setValue("INVOICE_DATE", model.getInvoiceRefDate());
				jcoTable.setValue("PMT_FLAG", model.getFullPartialFlag());
				jcoTable.setValue("EXCWHT", model.getChequeAmount());
				
				if(!CommonService.IsNull(model.getAdvReceiptNo()))
					jcoTable.setValue("ADV_RECEIPT_NO", model.getAdvReceiptNo());
				
				jcoTable.setValue("CARD_NO", model.getCardNo());
				jcoTable.setValue("BANK_KEY", model.getBankCardReader());
				jcoTable.setValue("PAY_CARD_TYP", model.getCreditCardType());				
				jcoTable.setValue("STATUS", model.getStatus());
				
				//For Rent Clear Adv
				jcoTable.setValue("ADV_CLR_ONLY", model.getRentAdvClrOnly());
				
	        }
		}
		super.SynchroToSap(jcoFunction, jcoTable, value_list);
	}
	
	@Override
	public void CallbackMessageFromSap(JCoTable jcoTable_return) throws Exception {
		// TODO Auto-generated method stub
		List<FiArinvoicereceOutb> lst = new ArrayList<FiArinvoicereceOutb>();				
		
			if(!jcoTable_return.isEmpty()){
				log.info("Update Message table Retrun getNumRows = " + jcoTable_return.getNumRows());
				for(int i = 0; i < jcoTable_return.getNumRows(); i++)
				{
					jcoTable_return.setRow(i);			
					FiArinvoicereceOutb model = fiArinvoicereceOutbServ.findById(CommonService.IsNullRNull(jcoTable_return.getString("PROMIS_TXN_ID")));
					//log.info("PROMIS_TXN_ID = " + jcoTable_return.getString("PROMIS_TXN_ID") + " // MSG_CODE : " + (CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")) == null ? " No Message." : CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE"))) + " // MSG_DESC : " + (CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")) == null ? " No Message." : CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC"))));
					log.info(CommonJCOReturn.toString(jcoTable_return));
					
					if(model != null){
						
						model.setMsgCode(CommonService.IsNullRNull(jcoTable_return.getString("MSG_CODE")));
						model.setMsgDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_DESC")));
						model.setMsgAltDesc(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ALT_DESC")));
						model.setMsgActResult(CommonService.IsNullRNull(jcoTable_return.getString("MSG_ACTION_RESULT")));
						model.setIsactive("Y");
						model.setIssync("Y");
						
						lst.add(model);
					}
				}
			}else
				log.info(CommonJCOReturn.toString(jcoTable_return));
			
			fiArinvoicereceOutbServ.Updated(lst);
			
		super.CallbackMessageFromSap(jcoTable_return);
	}
	
	private void UpdateStagingWhenError(List<FiArinvoicereceOutb> value_list, Exception error) throws Exception{
		log.info("Start UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		try{
			
			if(!CommonService.IsNull(value_list)){
				List<FiArinvoicereceOutb> newlst = new ArrayList<FiArinvoicereceOutb>();
				for(FiArinvoicereceOutb model : value_list)
				{				
					model.setMsgCode("E");
					model.setMsgDesc(CommonService.CutString(error.getMessage(), 3500));
					model.setIsactive("Y");
					model.setIssync("N");
					newlst.add(model);
				}
				
				new FiArinvoicereceOutbServices(this.emSynchro).Updated(newlst);
			}
			
		}catch(Exception e){
			log.error(e.getMessage());
			System.err.println(e.getMessage());
		}finally{
			log.info("End UpdateStagingWhenError Message Error size=" + CommonService.getSize(value_list));
		}
	}
	
	public void SendToSAP(List<FiArinvoicereceOutb> value_list) throws Exception
	{
		try{
			if(!CommonService.IsNull(value_list)){
				
				this.sap_bapi = "ZIN_FIAR_RECEIPT";
				this.sap_table = "ACCT_DATA";
				this.sap_table_return = "RETURN";
				this.jco_conn  = new Connection();
			
				fiArinvoicereceOutbServ = new FiArinvoicereceOutbServices(this.emSynchro);

				//Get SAP BAPI function 
				JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
				
				//Get SAP Staging table
				JCoTable jcoTable = jco_conn.getTables(sap_table);
				
				//List<FiArinvoicereceOutb> value_list = fiArinvoicereceOutbServ.findIsSync("N");
				SynchroToSap(jcoFunction, jcoTable, value_list);
				
				//Get SAP Staging table retrun message
				JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
				CallbackMessageFromSap(jcoTable_return);
				
			}
		}catch(Exception e){
			UpdateStagingWhenError(value_list, e);

			log.error(e.getMessage());
			System.err.println(e.getMessage());
			
			throw e;
		}
	}
	
	private void Start() throws Exception
	{
		this.sap_bapi = "ZSIN_AR_STAG_RECEIPT";
		this.sap_table = "ACCT_DATA";
		this.sap_table_return = "RETURN";
		this.jco_conn  = new Connection();
		

		//Get SAP BAPI function 
		JCoFunction jcoFunction = jco_conn.getJCoFunction(sap_bapi);
		
		//Get SAP Staging table
		JCoTable jcoTable = jco_conn.getTables(sap_table);
		fiArinvoicereceOutbServ = new FiArinvoicereceOutbServices(this.emSynchro);
		List<FiArinvoicereceOutb> value_list = fiArinvoicereceOutbServ.findIsSync("N");
		SynchroToSap(jcoFunction, jcoTable, value_list);
		
		//Get SAP Staging table retrun message
		JCoTable jcoTable_return = jco_conn.getTables(sap_table_return);
		CallbackMessageFromSap(jcoTable_return);
	}

//	/**
//	 * @param args
//	 */
//	public static void main(String[] args) {
//		// TODO Auto-generated method stub
//		
//		try{
//			
//			FiArinvoicereceOutbService obj = new FiArinvoicereceOutbService();
//			obj.Start();
//			
//		}catch(Exception ex)
//		{
//			ex.printStackTrace();
//			log.error(ex);	
//		}
//	}

}
